package com.example.webapp.service;

import com.example.webapp.entity.RequestHistory;
import com.example.webapp.repository.RequestHistoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Slf4j
@Service
public class HttpRequestService {
    @Autowired
    private RequestHistoryRepository requestHistoryRepository;
    
    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<String> sendRequest(String url, String method, 
            Map<String, String> headers, Map<String, String> params, String body) {
        try {
            // 构建URL（添加查询参数）
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            if (params != null) {
                params.forEach(builder::queryParam);
            }
            String finalUrl = builder.build().encode().toUriString();

            // 构建请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            if (headers != null) {
                headers.forEach(httpHeaders::add);
            }

            // 构建请求体
            HttpEntity<String> requestEntity = new HttpEntity<>(body, httpHeaders);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                finalUrl,
                HttpMethod.valueOf(method.toUpperCase()),
                requestEntity,
                String.class
            );
            
            // 保存请求历史
            RequestHistory history = new RequestHistory();
            history.setUrl(url);
            history.setMethod(method);
            history.setHeaders(headers.toString());
            history.setParams(params.toString());
            history.setRequestBody(body);
            history.setResponseStatus(response.getStatusCodeValue());
            history.setResponseBody(response.getBody());
            
            requestHistoryRepository.save(history);
            
            return response;
        } catch (Exception e) {
            log.error("Error sending request: ", e);
            throw e;
        }
    }

    public Page<RequestHistory> getRequestHistory(String url, String method, Pageable pageable) {
        if (url != null || method != null) {
            return requestHistoryRepository.findByUrlContainingAndMethodContainingOrderByCreatedAtDesc(
                url != null ? url : "", 
                method != null ? method : "", 
                pageable
            );
        }
        return requestHistoryRepository.findAllByOrderByCreatedAtDesc(pageable);
    }
} 